const routes = [
  {
    path: '/',
    component: 'layout/index',
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        component: 'views/dashboard/index',
        name: 'Dashboard',
        meta: { title: 'Dashboard', icon: 's-grid', affix: true }
      }
    ]
  },
  {
    path: '/user',
    component: 'layout/Layout',
    redirect: '/user/list',
    name: 'User',
    meta: {
      title: 'User',
      icon: 'user',
      roles: ['admin'] // 只有管理员可访问
    },
    children: [
      {
        path: '/user/list',
        component: 'views/user/list',
        name: 'UserList',
        meta: {
          title: 'User List',
          roles: ['admin'] // 只有管理员可访问
        }
      },
      {
        path: '/user/create-edit',
        component: 'views/user/create-edit',
        name: 'UserCreateEdit',
        meta: {
          title: 'Create User',
          roles: ['admin'] // 只有管理员可访问
        }
      }
    ]
  },
  {
    path: '/login',
    component: 'views/login/index',
    hidden: true
  },
  {
    path: '/profile',
    component: 'views/profile',
    hidden: true
  },
  {
    path: '/404',
    component: 'views/404',
    hidden: true
  },
  // ... 可能还有其他路由配置，比如404页面等
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

function filterRoutesByRoles(routes, roles) {
  const filteredRoutes = []

  for (const route of routes) {
    const hasAccess =
      !route.meta?.roles ||
      roles.some((role) => route.meta.roles.includes(role))

    if (hasAccess) {
      // 递归处理子路由
      const filteredChildren = route.children
        ? filterRoutesByRoles(route.children, roles)
        : undefined

      // 创建一个新的路由对象，并根据需要移除children属性
      const newRoute = { ...route }
      if (filteredChildren && filteredChildren.length === 0) {
        delete newRoute.children // 如果子路由为空数组，则移除children属性
      } else {
        newRoute.children = filteredChildren // 否则保留子路由
      }

      filteredRoutes.push(newRoute)
    }
  }

  return filteredRoutes
}
module.exports = {
  getRoutes(req, res) {
    const userRoles = req.query.roles || [] // 例如: ['admin']
    // 过滤路由，只保留用户有权访问的路由
    const userRoutes = filterRoutesByRoles(routes, JSON.parse(userRoles))

    // 返回用户的路由表
    res.json({
      code: 200,
      msg: userRoutes
    })
  }
}
